(function ($) {
    window.sysConfig = {
        isDebug: true
    }
    //进度条
    $.fn.extend({
        setProgressBarVal: function (value) {
            if (value) {
                value = isNaN(value) ? value : false || "string" === typeof value && value.endsWith("%") ? value.substring(0, value.length - 1) : value;
                if ((isNaN(value) && (value = parseInt(value)) || "number" === typeof value) && value >= 0 && value <= 100) {
                    var progressBar = $(this).find('.progress-bar').width(value + '%');
                    if (value <= 50) {
                        progressBar.addClass('progress-bar-danger');
                    } else if (value < 80) {
                        progressBar.addClass('progress-bar-warning').removeClass('progress-bar-danger');
                    } else if (value > 80) {
                        progressBar.addClass('progress-bar-success').removeClass('progress-bar-warning');
                    }
                    $(this).find('span').text(value + '% Complete');
                }
            }
        }
    });
    $.stopPropagation = function (e) {//可以让单击事件失效
        e = e || window.event;
        if (e.stopPropagation) { //W3C阻止冒泡方法
            e.stopPropagation();
        }
        if (e && e.preventDefault) {
            e.preventDefault();
        } else {
            e.cancelBubble = true; //IE阻止冒泡方法
        }
    }

    $.loginUser = undefined;//当前登录用户
    $.fileProgress = $(".loading-container .progress.progress-set-pos");
    $(document)
        .ajaxStart(function () {//全局的异步事件
            $(".loading-container").removeClass("loading-inactive");
        }).ajaxStop(function () {//全局的异步事件
            $(".loading-container").addClass("loading-inactive");
            $.fileProgress.addClass("progress-bar-con").setProgressBarVal(0);
        });

    //ajax封装
    $.sysAjax = function (opts) {
        var resBool = true;
        var TOKEN = "PCNODEJSMANAGER";//公钥
        var PRIVATE_TOKEN = "88990001";//私钥
        var AUTH_TOKEN = getAuthToken_5minute(TOKEN, PRIVATE_TOKEN);
        var opts_def = {
            url: "/users",
            type: "POST",
            beforeSend: undefined,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                Notify('出现错误!<br/>[' + XMLHttpRequest.status + '] ' + XMLHttpRequest.statusText, 'bottom-right', '5000', 'danger', 'fa-bug', true);
                resBool = false;
            },
            dataFilter: undefined,
            success: undefined,
            complete: undefined,
            async: true,
            cache: true,
            data: undefined,
            dataType: "JSON",
            global: true,
            timeout: 15000,//15s
            headers: {
                token: TOKEN,//公钥
                auth_token: AUTH_TOKEN //动态口令
            },
            isTip: true,
            files: undefined//{filename1:fileObj,filename2:file2Obj}

        }, opts = $.extend(opts_def, opts);
        if (opts.files) {
            opts.xhr = function () {
                var xhr = $.ajaxSettings.xhr();
                if (xhr.upload) {
                    $.fileProgress.removeClass("progress-bar-con");
                    xhr.upload.addEventListener("progress", function (event) {
                        $.fileProgress.setProgressBarVal(Math.floor(event.loaded / event.total * 100));
                        if (opts.onprogress)opts.onprogress(event);
                    }, false);
                    return xhr;
                }
            }
        }
        if (opts.data) {//文本参数加密
            var jsonDataStr = JSON.stringify(opts.data);
            if (window.sysConfig.isDebug) {
                opts.data = {"data": jsonDataStr};
            } else {
                var jsonDateEnc = pako.deflate(des.strEnc(jsonDataStr, TOKEN, PRIVATE_TOKEN, AUTH_TOKEN), {to: 'string'});
                opts.data = {"data": jsonDateEnc};
            }
        }
        if (opts.files) {
            var formData = new FormData();
            if (opts.data) {
                formData.append("data", encodeURI(opts.data.data));
            }
            $.map(opts.files, function (file, key) {
                formData.append(key, file, file.name);
            });
            opts.data = formData;
        }
        var call_success = opts.success;
        opts.success = function (data, textStatus, jqXHR) {
            if (data && data.status) {
                if (data.status === '0004') {//用户未登录
                    $.loginModal.loginShow();
                    return;
                }
                if (opts.isTip && data.msg && data.status == "0000") {
                    Notify("[" + data.status + "]" + data.msg, 'bottom-right', '5000', 'info', 'fa-info', true);
                } else if (opts.isTip && data.msg) {
                    Notify("[" + data.status + "]" + data.msg, 'bottom-right', '5000', 'warning', 'fa-warning', true);
                }
            }
            if (data && data.data) {
                if (window.sysConfig.isDebug) {
                    if (call_success)
                        call_success(data.data);
                } else {
                    var jsonDateDes = des.strDec(pako.inflate(data.data, {to: 'string'}), TOKEN, PRIVATE_TOKEN, AUTH_TOKEN);
                    if (call_success)
                        call_success(JSON.parse(jsonDateDes));
                }
            } else {
                if (call_success)
                    call_success();
            }
            resBool = true;
        }
        $.ajax(opts);
        return resBool;
    };

    $.loginModal = new function () {
        var
            $loginModal = $('#loginModal'),
            isShowModal = false;//默认登录的模式对话框是关闭的
        $loginModal.on('hide.bs.modal', function () {
            if ($.loginUser != undefined && isShowModal) {
                return true;
            }
            return false;
        });
        this.loginShow = function () {
            if (!isShowModal) {
                $.loginUser = undefined;
                isShowModal = true;//默认是对话框被打开
                $("body").addClass("bodyLoginModal");
                $(".modal-dialog", $loginModal).load("login.html");
                $loginModal.modal('show');
            }
        };

        this.doLogin = function (username, password, callback) {
            return $.sysAjax({
                url: "/users/login",
                data: {"username": username, "password": password},
                success: function (user) {
                    if (user) {
                        $.loginUser = user;
                        if ("function" === typeof  callback) {
                            callback(user);
                        }
                        //TODO 判断是否初始化系统数据
                        if ($.setUserInfoUiContent)$.setUserInfoUiContent($.loginUser);
                        if ($.initReloadMenu)$.initReloadMenu();
                    }
                }
            });
        };

        this.loginHide = function () {
            $("body").removeClass("bodyLoginModal");
            $("body div.modal-backdrop.fade.in").hide();
            $(".modal-dialog", $loginModal).html("");
            $loginModal.modal('hide');
            isShowModal = false;
        }
        this.userLogout = function () {
            $.sysAjax({
                url: "/users/logout",
                async: false,
                success: function () {
                    $.loginUser = undefined;
                    isShowModal = false;
                    $.loginModal.loginShow();
                }
            });
        }
    };
    $("#userLogout").click(function () {
        $.loginModal.userLogout();
    });

    //设置 登录用户人员的信息
    $.setUserInfoUiContent = function (user) {
        var u = user || $.loginUser;
        if (u) {
            var index_account_li = $("#index_account_li");
            var index_account_li_ul = $("#index_account_li_ul", index_account_li);
            $(".profile span", index_account_li).text(u.userInfoObj.nikename || '男神/女神');
            $(".username a", index_account_li_ul).text(u.userInfoObj.nikename || '男神/女神');
            $(".email a", index_account_li_ul).text(u.email || '');
        }
    }
    //获取用户是否登录---------------------------------------------
    $.sysAjax({
        url: "/users/loginUser",
        async: false,
        isTip: false,
        success: function (loginUser) {
            $.loginUser = loginUser;
            $.setUserInfoUiContent($.loginUser);
        }
    });

})(jQuery);